import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:my_app/global/global.dart';
import 'package:my_app/menu/menu.dart';
import 'package:my_app/common/common.dart';
import 'package:my_app/service/api/api.dart';

class Login extends StatefulWidget {
  @override
  _Login createState() => new _Login();
}

class _Login extends State<Login> {
  //获取Key用来获取Form表单组件
  GlobalKey<FormState> loginKey = new GlobalKey<FormState>();
  late String userName = '';
  late String password;
  bool isShowPassWord = false;
  int _muji = Common.muji;
  int apiNum = 10;
  @override
  initState() {
    getApiUrl();
    super.initState();
    // Map userinfo = {"userName":"张三","age":20};
  }

  // 获取api地址
  void getApiUrl() async {
    var data = await ApiService.getApiUrl();
    if (data.toString().substring(0, 1) == "1") {
      GlobalData.apiUrl = data.toString().substring(2) + "/";
    } else {
      if (apiNum > 0) {
        apiNum--;
        getApiUrl();
      } else {
        Common.showTost("接口获取失败请检查网络");
      }
    }
    print("接口地址：");
    print(data);
    print("保存接口地址：");
    print(GlobalData.apiUrl);
  }

  void login() async {
    if (GlobalData.apiUrl == "") {
      Common.showTost("接口获取失败请检查网络后重试");
      getApiUrl();
      return;
    }
    FocusScope.of(context).requestFocus(FocusNode());
    try {
      //读取当前的Form状态
      var loginForm = loginKey.currentState;
      //验证Form表单
      if (loginForm!.validate()) {
        loginForm.save();
        if (userName == '' || password == '') {
          Common.showTost('用户名或密码不能为空');
        } else {
          print('userName: ' + userName + ' password: ' + password);
          var data = await ApiService.login(userName, password);

          // Timer(Duration(seconds: 5), () {
          //   print(123);
          // });
          // Future.delayed(Duration(milliseconds: 5000), () {
          // try {} catch (err) {

          // }
          if (data[0]["ERROR_MSG"] != null) {
            Common.showTost(data[0]["ERROR_MSG"]);
          } else {
            // 保存登录数据
            GlobalData.staffName = data[0]["STAFF_NAME"];
            GlobalData.vendorID = data[0]["VENDOR_ID"];
            GlobalData.staffID = data[0]["STAFF_ID"];
            // Navigator.of(context).popAndPushNamed("menu");
            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
              return Menu();
            }));
            // Navigator.pushAndRemoveUntil(context,
            //     new MaterialPageRoute(builder: (BuildContext context) {
            //   return Menu();
            // }), (route) => route == null);
          }
          // });
          // Common.showTost(data.toString());

        }
      } else {
        print('用户名或密码不能为空');
      }
    } catch (err) {
      Common.showTost(err.toString());
    }
  }

  void showPassWord() {
    setState(() {
      isShowPassWord = !isShowPassWord;
    });
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mq;
    mq = MediaQuery.of(context);
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: '登录',
      home: new Scaffold(
        body: ListView(
          children: [
            Column(
              children: <Widget>[
                new Container(
                    padding: EdgeInsets.only(top: 40.0, bottom: 10.0),
                    child: new Text(
                      'MUJI',
                      style: TextStyle(color: Color(_muji), fontSize: 40.0),
                    )),
                new Container(
                  padding: const EdgeInsets.all(16.0),
                  child: new Form(
                    autovalidateMode: AutovalidateMode.always,
                    key: loginKey,
                    child: new Column(
                      children: <Widget>[
                        new Container(
                          decoration: new BoxDecoration(
                              border: new Border(
                                  bottom: BorderSide(
                                      color: Color.fromARGB(255, 240, 240, 240),
                                      width: 1.0))),
                          child: new TextFormField(
                            keyboardType: TextInputType.emailAddress,
                            decoration: new InputDecoration(
                              labelText: '请输入用户名',
                              labelStyle: new TextStyle(
                                  fontSize: 15.0,
                                  color: Color.fromARGB(255, 93, 93, 93)),
                              border: InputBorder.none,

                              // suffixIcon: new IconButton(
                              //   icon: new Icon(
                              //     Icons.close,
                              //     color: Color.fromARGB(255, 126, 126, 126),
                              //   ),
                              //   onPressed: () {

                              //   },
                              // ),
                            ),
                            onSaved: (value) {
                              userName = value!;
                            },
                            validator: (phone) {
                              // if(phone.length == 0){
                              //   return '请输入手机号';
                              // }
                            },
                            onFieldSubmitted: (value) {},
                          ),
                        ),
                        new Container(
                          decoration: new BoxDecoration(
                              border: new Border(
                                  bottom: BorderSide(
                                      color: Color.fromARGB(255, 240, 240, 240),
                                      width: 1.0))),
                          child: new TextFormField(
                            keyboardType: TextInputType.emailAddress,
                            decoration: new InputDecoration(
                              labelText: '请输入密码',
                              labelStyle: new TextStyle(
                                  fontSize: 15.0,
                                  color: Color.fromARGB(255, 93, 93, 93)),
                              border: InputBorder.none,
                              // suffixIcon: new IconButton(
                              //   icon: new Icon(
                              //     isShowPassWord
                              //         ? Icons.visibility
                              //         : Icons.visibility_off,
                              //     color: Color.fromARGB(255, 126, 126, 126),
                              //   ),
                              //   onPressed: showPassWord,
                              // )
                            ),
                            obscureText: !isShowPassWord,
                            onSaved: (value) {
                              password = value!;
                            },
                          ),
                        ),
                        new Container(
                          height: 45.0,
                          margin: EdgeInsets.only(top: 40.0),
                          child: new SizedBox.expand(
                            child: new ElevatedButton(
                              style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.all(Color(_muji)),
                              ),
                              onPressed: login,
                              child: new Text('登录'),
                              // color: Color(_muji),
                              // child: new Text(
                              //   '登录',
                              //   style: TextStyle(
                              //       fontSize: 14.0,
                              //       color: Color.fromARGB(255, 255, 255, 255)),
                              // ),
                              // shape: new RoundedRectangleBorder(
                              //   borderRadius: new BorderRadius.circular(4335.0),
                              // ),
                            ),
                          ),
                        ),
                        // new Container(
                        //   margin: EdgeInsets.only(top: 30.0),
                        //   padding: EdgeInsets.only(left: 8.0, right: 8.0),
                        //   child: new Row(
                        //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        //     children: <Widget>[
                        //       new Container(
                        //         child: Text(
                        //           '注册账号',
                        //           style: TextStyle(
                        //               fontSize: 13.0,
                        //               color: Color.fromARGB(255, 53, 53, 53)),
                        //         ),
                        //       ),
                        //       Text(
                        //         '忘记密码？',
                        //         style: TextStyle(
                        //             fontSize: 13.0,
                        //             color: Color.fromARGB(255, 53, 53, 53)),
                        //       ),
                        //     ],
                        //   ),
                        // ),
                      ],
                    ),
                  ),
                ),
                Container(
                  padding:
                      EdgeInsets.only(top: mq.size.height - 400, bottom: 10.0),
                  child: Text("v1.0.7"),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
